Constructors & Destructors
Constructor is a special member function, because whose name is the same as class name.
Program on Constructors
using System;
class abc
{
int a,b;
public abc()
{
Console.WriteLine("Enter 2 nos");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
}
public void put()
{
Console.WriteLine("Sum" + (a + b));
}
}
class sample
{
public static void Main()
{
abc x = new abc();
x.put();
}
}
Program on Parameterized constructor
using System;
class abc
{
int a,b;
public abc(int x,int y)
{
a = x;
b = y;
}
public void put()
{
Console.WriteLine("Sum" + (a + b));
}
}
class sample
{
public static void Main()
{
abc x = new abc(4,5);
x.put();
}
}
Program on over loading Constructors.
using System;
class abc
{
int a,b;
public abc()
{
Console.WriteLine("Default Constructor");
}
public abc(int x,int y)
{
a = x;
b = y;
}
public abc(int x, double y)
{
Console.WriteLine("Sum" + (x + y));
}
public void put()
{
Console.WriteLine("Sum" + (a + b));
}
}
class sample
{
public static void Main()
{
abc x = new abc(4,5);
abc y = new abc();
abc z = new abc(4, 7.2);
x.put();
}
}
Program on to find the area of triangle, circle, and simple interest using constructors.
Program on destructors
using System;
class abc
{
public abc()
{
Console.WriteLine("Constructor created");
}
~abc()
{
Console.WriteLine("This is Destructor");
}
}
class sample
{
public static void Main()
{
abc x = new abc();
abc y = new abc();
{
abc z = new abc();
}
}
}